package org.windblog.core.servlet.file;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.windblog.core.FileService;
import org.windblog.core.entity.File;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);

		BlobKey blobKey = blobs.get("theFile");

		String title = req.getParameter("title");
		String description = req.getParameter("description");
		
		if (blobKey == null) {
			res.sendRedirect("/admin/mediaLibrary.jsp?message=1");
		} else {
			File file = new File();
			
			file.setAuthor(UserServiceFactory.getUserService().getCurrentUser().getEmail());
			file.setTitle(title);
			file.setDescription(description);
			file.setBlobKey(blobKey);
			
			FileService.setFile(file);
			
			res.sendRedirect("/admin/mediaLibrary.jsp?message=2");
		}
	}
}
